var nowtab = 1;
var mx;
var my;
var feedct;
var need_fill_info = 0;
var check_js_var = 0;
var need_to_be_one = 0;
var clicktype = 0;
function setPos(e) {
    mx = e.client.x;
    my = e.client.y;
}
function showProduct(id) {
	if (!is_user_login) {
	/*if (!is_user_login && id != 75) {*/
		//only sina will - 0 
		goSinaLoginFrame('details', id);
	} else {
    	showBox(platfrom_base_req_url + "/Product/getProductDetail?g_product_id=" + id);
	}
}
function showChangeProduct(id) {
	if (!is_user_login) {
		//only sina will - 0 
		goSinaLoginFrame('convertdetails', id);
	} else {	
    	showBox(platfrom_base_req_url + "/Product/getChangeProductDetail?g_product_id=" + id);
	}
}


function showBox(url, w , h) {
    w = !w?700:w;
    h = !h?660:h;
    
    $('fake_a_div').empty();
    fake_a = new Element("a", {href: url, 'rel':'lightbox[external '+w+' '+h+']'}).injectInside($('fake_a_div'));
	$(fake_a).mediabox({/* Put custom options here */}, null, function(el) {
		var rel0 = this.rel.replace(/[[]|]/gi," ");
		var relsize = rel0.split(" ");
		return (this == el) || ((this.rel.length > 8) && el.rel.match(relsize[1]));
	});  
	$(fake_a).fireEvent('click',0,10);
}
function showAlert(content, type, w, h) {
    type = !type?'text':type;
    if (type=='text'){
        w = !w?337:h;
        h = !h?169:h;        
        url = 'text::' + content ;
    } else if (type=='img'){
        url = content;
    } else if (type=='url'){
        w = !w?518:h;
        h = !h?400:h;        
        url = content;
    }
    
    $('fake_a_div').empty();
    fake_a = new Element("a", {href: url, 'rel':'lightbox[external '+w+' '+h+']'}).injectInside($('fake_a_div'));
	$(fake_a).mediabox({/* Put custom options here */}, null, function(el) {
		var rel0 = this.rel.replace(/[[]|]/gi," ");
		var relsize = rel0.split(" ");
		return (this == el) || ((this.rel.length > 8) && el.rel.match(relsize[1]));
	});  
	$(fake_a).fireEvent('click',0,10);
}
function ajaxLoad(div, url, callback) {
    url = platfrom_base_req_url + url;
    xLoadContent(div, url, callback);
}
function doPost(url,nameOfForm,displayIds,callback ) {
    url = platfrom_base_req_url + url;
    if (!nameOfForm) {
        xLoadContent(displayIds, url, callback);
    } else {
        xPostContent(displayIds, nameOfForm, url, callback);
    }
}
function xPostContent(el, nameOfForm, o_url, callback) {
	if ($(el) && $(el).innerHTML == ''){
		$(el).innerHTML = '<div class="loading_div"></div>';
	}
	var request = new Request({
		url: o_url,
		method:'post',
		data: $(nameOfForm).toQueryString(),
		onComplete: function(text) {
			var html;
			var script_e;
			if (callback) {
			    setTimeout(callback,1);
			}			
			try {
				html = text.stripScripts(function(script){
					script_e = script;
				});
				if ($(el)) {
				    $(el).innerHTML = html;
				}
				$exec(script_e);
			}catch (e){

			}
			Mediabox.scanPage();

		}
	});
	request.processScripts = function (text){return text;};//for js
	request.send();    
}
function xLoadContent(el,o_url,callback){

	if ($(el) && $(el).innerHTML == ''){
		$(el).innerHTML = '<div class="loading_div"></div>';
	}
	var request = new Request({
		url: o_url,
		method:'get',
		onComplete: function(text) {
			var html;
			var script_e;
			if (callback) {
			    setTimeout(callback,1);
			}			
			try {
				html = text.stripScripts(function(script){
					script_e = script;
				});
				if ($(el)) {
				    $(el).innerHTML = html;
				}
				$exec(script_e);
			}catch (e){

			}
			Mediabox.scanPage();

		}
	});
	request.processScripts = function (text){return text;};//for js
	request.send();
}
function viewFriendInfo(user_id){
	
	var urlUserInfo = "/user/getUserInfo/"+user_id;
	doPost(urlUserInfo,'','userInfoDiv');
	
}

function showNextPic(){
	nowpic ++;
	if (document.getElementById('PicSL_'+nowpic)){

	}else {
		nowpic = 0;
	}
	changeImg(nowpic);
}

function changeImg(n){

	var imgObj =document.getElementById('productImgId');
	var imgObjSmall =document.getElementById('PicSL_'+n);
	if (imgObjSmall){
		imgObj.src = imgObjSmall.src;
	}else {
	}

}

 /**
  * gets the contents of the form as a URL encoded String
  * suitable for appending to a url
  * @param formName to encode
  * @return string with encoded form values , beings with &
  */ 
 function getFormAsString(formName) {
 	return $(formName).toQueryString();
 }
 
function freeProductShowCat(cat){
	var next = 1;
	var url = "/user/productFreeList/"+cat+"?curPage="+next;
	doPost(url,'','productFreeDiv');	
}

function refreshSelf(){
	document.location.href=document.location.href + '&type=' + 0;
}
function hl_menu_li(id) {
    var temp=['menu_ma','menu_mb','menu_mc','menu_md','menu_me', 'menu_mf', 'menu_mg'];
    for (i in temp) {
        if ($(temp[i])) {
            $(temp[i]).className = '';
        }
    }
    if (id) {
        $(id).className = 'now';
    }
}
function loadLuckUser(p){
    p = !p ? 1:p;
    ajaxLoad('msgDynDiv','/user/ajaxListLuckUsers/'+p+'?r='+Math.random());
}
function loadRightContent() {
    setTimeout(function () {
        ajaxLoad('userInfoDiv','/user/getUserInfo');
    },100);    
    setTimeout(function () {
        loadLuckUser(1);
    },200);
    setTimeout(function () {
        ajaxLoad('friendListDiv','/user/ajaxListRecentApply'+'?r='+Math.random());
    },500);   
    
}


function getRadioValue(na){

	var temp=document.getElementsByName(na);
	var sel = '';
	for (i=0;i<temp.length;i++){  //遍历Radio
		if(temp[i].checked)      {
			sel = temp[i].value;
		}
	}
	return sel;
}

Array.prototype.contain = function(e)
{
for(i=0;i<this.length && this[i]!=e;i++);
return !(i==this.length);
}


function getElementByClassW(classname) {
   var elements = [];
   var alltags = document.all ? document.all : document.getElementsByTagName("*")
   for (var i=0; i<alltags.length; i++){
      var classNames = alltags[i].className.split(" ");
      if (classNames.contain(classname))
          elements[elements.length] = alltags[i];
   }
   return elements;
}

function showMessageInBox(a,msg,b){
	var loading = document.getElementById('myConvertDoing');
	var bt = document.getElementById('myConvertBy');
	var info = document.getElementById('myConvertInfo');
	var infov = document.getElementById('myConvertInfoView');
	var flashcon = document.getElementById('flashcon');
	flashcon.style.display = 'none';
	loading.style.display = 'none';
	bt.style.display = 'none';
	info.style.display = '';
	
	if (msg.indexOf('成功')>0){
	   infov.style.display = '';
	
		if (msg.indexOf('申请成功')>0){
			$('cyFillInfo_p').style.display = '';
		}
	} else {
		loadRightContent();
	}
	info.innerHTML = msg;
	if (feedct){
	   sendFeed(feedct);
    }

}
function showMessageInBoxFlash(myshake,msg){
	if(1==myshake){
		if (typeof(luck_code) == 'undefined'){
			doPost('/user/showFillInfo', '', 'cyFillInfo');
		} else {
			doPost('/user/showFillCaptchaInfo/'+luck_code, '', 'cyFillInfo');
		}
	}

	var flashcon = document.getElementById('flashcon');
	flashcon.style.display = '';

	var url = '/webroot/image/sk.swf?myshake='+myshake+'&msg='+msg;
	var flashvars = {};
	var params = {menu:"false",wmode:"transparent"};
	var attributes = {};
	swfobject.embedSWF(url, "flashcon_t", "300", "300", "9.0.0", false, flashvars, params, attributes);
}

var clicktype;
function initClick(xclicktype){
    clicktype = !xclicktype?0:xclicktype;
    check_js_var = 1;
    need_to_be_one=0;
}
function setClickIt(){
    need_to_be_one = 1;
    check_js_var = 0;
}

function saveEditInfo(form_name, form_write_name){
    form_name = !form_name?'update_info':form_name;
    form_write_name = !form_write_name?'user_info_edit_hint':form_write_name;
    doPost('/user/saveFillInfo',form_name,form_write_name);
}
function showEditInfo(){
    $('user_info_view').setStyle('display','none');
    $('user_info_edit').setStyle('display','');
}
function cancelEditInfo(){
    $('user_info_view').setStyle('display','');
    $('user_info_edit').setStyle('display','none');   
}
function myLuckShowTab(n) {
    alltab = [1,2,3];
    for (i in alltab) {
        tabid = alltab[i];
        if (isNaN(tabid)){
            continue;
        }
        if (tabid==n) {
            $('myluck_bt'+tabid).removeClass('applytab_bt_x');
            $('myluck_bt'+tabid).addClass('applytab_bt_now');
            $('myluck_ct'+tabid).setStyle('display','');
        } else {
            $('myluck_bt'+tabid).removeClass('applytab_bt_now');
            $('myluck_bt'+tabid).addClass('applytab_bt_x');            
            $('myluck_ct'+tabid).setStyle('display','none');
        }
    }
    nowtab = n;
}
function setLuckReceive(id, type, kuaidi_type) {
    kuaidi_type = !kuaidi_type?'':kuaidi_type;
    if (confirm('确认吗？')) {
        ajaxLoad('luck_hidden_submit', '/user/ajaxSetLuckReceive/'+id+'/'+type+'/'+kuaidi_type,
        function () {
            goMyluck(nowtab);
            if (kuaidi_type=='daofu') {
                showAlert('您已经成功发送领取宝贝请求，我们会在5个工作日发货，详情请见快递查询。');
            } else if (kuaidi_type=='ziqu') {
                showAlert('您已成功发送快递请求，请务必在5个工作日内派快递来取件。');
            } else {
                showAlert('操作成功！');
            }
        }
        );
        
    }
    
}
function luckCheckAll() {
    $$("#kuaidi_not_send_list input[type=checkbox]").each(function(e){
        e.checked = true;
    });
}
function showSelectKuaidi() {
    showAlert('/user/showSelectKuaidi', 'url');
}
function sendKuaidi(kuaidi_type) {
    if (!kuaidi_type) {
        showAlert('请先选择一种快递方式');
    }
    all = [];
    $$('#kuaidi_not_send_list input[type=checkbox]').each(function(e){
        if (e.checked){
            all.push(e.value);
        }
    });
    if (all.join(',')){
        setLuckReceive(all.join(','),1,kuaidi_type);
    } else {
        showAlert('请选择需要快递的宝贝。');
    }
}
function saveWhyNotGet(formid) {
    formid = !formid?'why_not_get_form':formid;
    doPost('/user/saveWhyNotGet', formid, 'fake_a_div');
}

function showAlertWhyNotGet(id) {
    showAlert('/user/showAlertWhyNotGet/'+id, 'url');
}

function showSaveShare(id) {
    showAlert('/user/showSaveShare/'+id, 'url');
}
function saveShare(formid, callback_div) {
    formid = !formid?'share_box':formid;
    callback_div = !callback_div?'share_callback':callback_div;
    $(formid).submit();

}
var noobSlide=new Class({initialize:function(a){this.items=a.items;this.mode=a.mode||'horizontal';this.modes={horizontal:['left','width'],vertical:['top','height']};this.size=a.size||240;this.box=a.box.setStyle(this.modes[this.mode][1],(this.size*this.items.length)+'px');this.button_event=a.button_event||'click';this.handle_event=a.handle_event||'click';this.onWalk=a.onWalk||null;this.currentIndex=null;this.previousIndex=null;this.nextIndex=null;this.interval=a.interval||5000;this.autoPlay=a.autoPlay||false;this._play=null;this.handles=a.handles||null;if(this.handles){this.addHandleButtons(this.handles)}this.buttons={previous:[],next:[],play:[],playback:[],stop:[]};if(a.addButtons){for(var b in a.addButtons){this.addActionButtons(b,$type(a.addButtons[b])=='array'?a.addButtons[b]:[a.addButtons[b]])}}this.fx=new Fx.Tween(this.box,$extend((a.fxOptions||{duration:500,wait:false}),{property:this.modes[this.mode][0]}));this.walk((a.startItem||0),true,true)},addHandleButtons:function(a){for(var i=0;i<a.length;i++){a[i].addEvent(this.handle_event,this.walk.bind(this,[i,true]))}},addActionButtons:function(a,b){for(var i=0;i<b.length;i++){switch(a){case'previous':b[i].addEvent(this.button_event,this.previous.bind(this,[true]));break;case'next':b[i].addEvent(this.button_event,this.next.bind(this,[true]));break;case'play':b[i].addEvent(this.button_event,this.play.bind(this,[this.interval,'next',false]));break;case'playback':b[i].addEvent(this.button_event,this.play.bind(this,[this.interval,'previous',false]));break;case'stop':b[i].addEvent(this.button_event,this.stop.bind(this));break}this.buttons[a].push(b[i])}},previous:function(a){this.walk((this.currentIndex>0?this.currentIndex-1:this.items.length-1),a)},next:function(a){this.walk((this.currentIndex<this.items.length-1?this.currentIndex+1:0),a)},play:function(a,b,c){this.stop();if(!c){this[b](false)}this._play=this[b].periodical(a,this,[false])},stop:function(){$clear(this._play)},walk:function(a,b,c){if(a!=this.currentIndex){this.currentIndex=a;this.previousIndex=this.currentIndex+(this.currentIndex>0?-1:this.items.length-1);this.nextIndex=this.currentIndex+(this.currentIndex<this.items.length-1?1:1-this.items.length);if(b){this.stop()}if(c){this.fx.cancel().set((this.size*-this.currentIndex)+'px')}else{this.fx.start(this.size*-this.currentIndex)}if(b&&this.autoPlay){this.play(this.interval,'next',true)}if(this.onWalk){this.onWalk((this.items[this.currentIndex]||null),(this.handles&&this.handles[this.currentIndex]?this.handles[this.currentIndex]:null))}}}});
 var AjaxUpload = new Class({
      initialize: function(form,url,data){
         this.form = $(form);
         if(this.form.getTag()!='form'){
             alert('is not form');
             this.form = null;
             return this;
         }
         if(this.form.encoding){
             this.form.setAttribute('encoding','multipart/form-data');
         }else{
             this.form.setAttribute('enctype','multipart/form-data');
         }
         this.form.setAttribute('method','post');
         this.form.getAttribute('action')||this.form.Attribute('action',url);
         this.processId = 'ajaxupload_'+Math.floor(Math.random()*10000);
         this.target = (new Element('iframe',{
              styles:{
                  width:0,
                  height:0,
                  border:0,
                  visibility:'hidden',
                  position:'absolute'
             },
              name: this.processId,
              id: this.processId,
              src:   window.ie ? 'javascript:false' : 'about:blank'
         })).inject(document.body);
         this.form.setProperty('target',this.processId);
         this.appendElements = [];
         this.appendElements.push(this.target);
         this.appendData({ajax:1});
         this.appendData(data);
     },
      appendData:function(data){
        if($type(data)=='string'){
            var value = data.split('&');
            data = {};
            for(var i=0; i < value.length; i++){
                var pos = value[i].indexOf('=');
                data[value[i].substring(0,pos)] = value[i].substring(pos+1);
            }
        }
        for(var key in data){
             this.appendElements.push((new Element('input',{
                  type:'hidden',
                  name:key,
                  value:data[key]
             })).inject(this.form));
         }
     },
      upload:function(){
        try{
            this.form.submit();
        }catch(e){
            return this.onError(e);
        }
        this.timer = (function(){
            try{
                //var doc = this.target.contentDocument||document.frames[this.processId].document;
                var doc = this.target.contentWindow.document||this.target.contentDocument;
                if(!doc) return;
                var location = window.opera ? this.target.location : doc.location;
            }catch(e){
                this.timer = $clear(this.timer);
                return this.onError(e);
            }
            if(!location||location=='about:blank'){
                return;
            }else{
                this.timer = $clear(this.timer);
                this.responseText = doc.body?doc.body.innerHTML:doc.documentElement.textContent;
                this.responseXML   = doc.XMLDocument||doc;
                this.fireEvent('onFinish',[this.responseText,this.responseXML]);
                this.cancel();
            }
        }).periodical(window.opera ? 150 : 100,this);
        return this;
     },
      onError:function(error){
         this.fireEvent('onError',error);
         this.fireEvent('onFinish',null);
         this.cancel();
         return this;
     },
      cancel:function(){
          $clear(this.timer);
         this.target.location = 'about:blank';
         this.appendElements.forEach(function(el){el.remove();});
     }
 });
 AjaxUpload.implement(new Events);
 Element.extend({
      upload:function(){
         return new AjaxUpload(this).upload();
     }
 });
